package com.leyou.sms.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.sms.config.SmsConstants;
import com.leyou.sms.config.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class SendSmsHelper {

    @Autowired
    private SmsProperties smsProp;

    @Autowired
    private IAcsClient client;

    /**
     * 发送短信验证码的工具类
     * @param phone 发给谁
     * @param code 验证码
     */
    public void sendSms(String phone, String code){
        log.info("【短信工具类】开始执行！");
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(smsProp.getDomain());
        request.setVersion(smsProp.getVersion());
        request.setAction(smsProp.getAction());
        request.putQueryParameter(SmsConstants.SMS_PARAM_REGION_ID, smsProp.getRegionID());
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_PHONE, phone);
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_SIGN_NAME, smsProp.getSignName());
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_TEMPLATE_CODE, smsProp.getVerifyCodeTemplate());
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_TEMPLATE_PARAM, "{\""+smsProp.getCode()+"\":\""+code+"\"}");
        try {
            //发短信
            CommonResponse response = client.getCommonResponse(request);
            //将返回结果转成Map
            Map<String, String> respMap = JsonUtils.toMap(response.getData(), String.class, String.class);
            //获取返回的状态码
            String respCode = respMap.get(SmsConstants.SMS_RESPONSE_KEY_CODE);
            if(StringUtils.equals(respCode, SmsConstants.OK)){
                log.info("【短信工具类】执行成功！手机用户"+phone+"已经接收到了验证码。");
            }else {
                throw new LyException(ExceptionEnum.SEND_MESSAGE_ERROR);
            }
        } catch (ServerException e) {
            //方便我们自己在控制台看真实异常
            log.error("【短信工具类】发送短信失败！阿里云服务器异常！异常信息为：{}", e.getMessage());
            //把异常再次抛出，让mq消息回执
            throw new LyException(ExceptionEnum.SEND_MESSAGE_ERROR);
        } catch (ClientException e) {
            //方便我们自己在控制台看真实异常
            log.error("【短信工具类】发送短信失败！乐优短信微服务异常！异常信息为：{}", e.getMessage());
            throw new LyException(ExceptionEnum.SEND_MESSAGE_ERROR);
        }
    }
}
